package com.xmkj.bearbiz.mine.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.common.BearBean.DaoGouPKBean;
import com.common.BearMethods.GetDaoPKMethods;
import com.common.BearMethods.ModifyInfoMethods;
import com.common.Entity.UserEntity;
import com.common.base.Constants;
import com.common.cons.Constans;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.entity.bean.UserDetailsBean;
import com.common.retrofit.entity.result.UpLoadPicEntity;
import com.common.retrofit.method.UpdateAddressMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.SPUtils;
import com.common.utils.SortUtils;
import com.common.widget.dialog.CommonDialog;
import com.common.widget.imageview.image.ImageLoaderUtils;
import com.common.widget.navigation.WidgetButton;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xmkj.bearbiz.R;
import com.xmkj.bearbiz.count.LoginActivtiy;
import com.xmkj.bearbiz.utils.BottomPickerUtils;
import com.xmkj.bearbiz.utils.CreateBmpFactory;
import com.xmkj.bearbiz.utils.GraphicsBitmapUtils;
import com.xmkj.bearbiz.utils.HandlerHelper;
import com.xmkj.bearbiz.utils.HttpURLConnHelper;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by chen on 2018/3/28.
 */

public class InfoCompileActivity extends BaseMvpActivity {
    @BindView(R.id.iv_face)
    ImageView mIvFace;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.et_person)
    EditText etPerson;

    @BindView(R.id.iv_next)
    ImageView mIvNext;
    @BindView(R.id.tv_sex)
    TextView mTvSex;
    @BindView(R.id.rl_sex)
    RelativeLayout mRlSex;
    @BindView(R.id.iv_next1)
    ImageView mIvNext1;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.rl_date)
    RelativeLayout mRlDate;
    @BindView(R.id.rl_address)
    RelativeLayout mRlAddress;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rl_name)
    RelativeLayout rlName;
    @BindView(R.id.tv_logout)
    TextView tv_logout;
    @BindView(R.id.tv_invadecode)
    TextView tv_invadecode;



    private String birth;
    private OptionsPickerView siteTypePicker;
    private List<String> siteTypeStrList = new ArrayList<>();
    private String person_sex;
    private UserDetailsBean info;
    private UserEntity entity;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_compile_info;
    }

    @Override
    protected void onViewCreated() {
        setRightNavigationText();
    }

    @Override
    protected void doLogicFunc() {
        attachClickListener(mRlDate);
        attachClickListener(mRlSex);
        attachClickListener(mIvFace);
        attachClickListener(mRlAddress);
        attachClickListener(rlName);
        attachClickListener(tv_logout);
        initSexOptionsPicker();
//        gotoGetUserInfo();
        tv_invadecode.setText(SPUtils.getShareString(Constans.INVITATION_CODE));

        initData();
        getName();

    }

    private void getName() {
        CommonSubscriber<DaoGouPKBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                DaoGouPKBean bean = (DaoGouPKBean) o;
                if(EmptyUtils.isNotEmpty(bean.mystar.nickname)){
                    mEtName.setText(bean.mystar.nickname);
                    SPUtils.setShareString(Constants.USERNAME, bean.mystar.nickname);

                }else {
                    mEtName.setText("");
                }

            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

//        jpushid = JPushInterface.getRegistrationID(this);
        GetDaoPKMethods.getInstance().daogouPK(subscriber, SPUtils.getShareInt(Constans.UID) + "", SPUtils.getShareString(Constans.HASHID));
        rxManager.add(subscriber);
    }

    private void initData() {
        if (EmptyUtils.isNotEmpty(SPUtils.getShareString(Constants.USERIMG))) {
            ImageLoaderUtils.displayCircle(mIvFace, SPUtils.getShareString(Constants.USERIMG));
        }
        if (EmptyUtils.isNotEmpty(SPUtils.getShareString(Constants.USERIMGID))) {
            face_id = SPUtils.getShareString(Constants.USERIMGID);
        }

        if (EmptyUtils.isNotEmpty(SPUtils.getShareString(Constants.USERIMGPERSON))) {
            etPerson.setText(SPUtils.getShareString(Constants.USERIMGPERSON));
        }

    }



    @Override
    protected void onViewClicked(View view) {
        if (view.getId() == mRlDate.getId()) {
            goChooseBirthDay();
        } else if (view.getId() == mRlSex.getId()) {
            if (siteTypePicker != null) {
                siteTypePicker.show();
            }
        } else if (view.getId() == mIvFace.getId()) {
            if (mCreateBmpFactory == null) {
                mCreateBmpFactory = new CreateBmpFactory(this);
            }
            AndPermission.with(this)
                    .requestCode(105)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                    .rationale(mRationaleListener)
                    .send();
        } else if (view.getId() == mRlAddress.getId()) {
            BottomPickerUtils.showCityPicker(this, new BottomPickerUtils.CityOptionPickerCallback() {
                @Override
                public void onOptionSelect(String option1, String option2, String option3) {
//                    tvSheng.setText(option1);
//                    tvShi.setText(option2);
//                    tvXian.setText(option3);
//                    has_choose_address = true;
//                    province_str = option1;
//                    city_str = option2;
//                    area_str = option3;
                    gotoUpdateAddress(option1 + " " + option2 + " " + option3);
                 /*   tvAddress.setText(option2+"");*/

                }
            });

        } else /*if (view.getId() == rlName.getId()) {
            Intent intent = new Intent(context, ModifyNameActivity.class);
            intent.putExtra(ModifyNameActivity.NAME, entity.username);
            startActivity(intent);
        } else*/ if (tv_logout.getId() == view.getId()) {
            showgoBackDialog();
        }
    }

    private void showgoBackDialog() {
        final CommonDialog dialog = newCommonDialog("你确实退出当前账号？");
        dialog.setSubmit(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*DataCenter.getInstance().deleteLoginDataInfo();
                EMClient.getInstance().logout(true);
                ActivityStack.getInstance().finishAllActivity();
                gotoActivity(LoginActivity.class);
                onBackPressed();*/
                SPUtils.setShareInt(Constans.UID, Integer.MAX_VALUE);
                SPUtils.setShareString(Constans.HASHID, "");
                SPUtils.setShareString(Constans.USERNAME, "");
                SPUtils.setShareString(Constans.HX_USERNAME, "");
                SPUtils.setShareString(Constans.HX_PASSWORD, "");
                SPUtils.setShareString(Constans.FACADE, "");
                SPUtils.setShareString(Constans.EMAIL, "");
                SPUtils.setShareString(Constans.DETAILS_ID, "");
                SPUtils.setShareString(Constants.USERNAME, "");
                SPUtils.setShareInt(Constans.FIRST, Integer.MAX_VALUE);
                onBackPressed();
                dialog.dismiss();
                gotoActivity(LoginActivtiy.class);

            }
        });
    }

    private void gotoUpdateAddress(final String adress) {
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {

                dismissProgressDialog();

                tvAddress.setText(adress);

            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                /*               swipRefresh.setRefreshing(false);*/


                showToastMsg(e);
            }
        });
        uid = SPUtils.getShareInt(Constans.UID);
        hashid = SPUtils.getShareString(Constans.HASHID);
        UpdateAddressMethods.getInstance().updateAddress(subscriber, uid, hashid, adress);
        rxManager.add(subscriber);
    }

    private void setRightNavigationText() {
        m_navigationBar.setVisibility(View.VISIBLE);
        WidgetButton widgetButton = new WidgetButton(this, R.string.save);
        widgetButton.getTextView().setTextColor(getResources().getColor(R.color.black));
        widgetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             /*   if (EmptyUtils.isEmpty(getEditTextStr(mEtName)) || EmptyUtils.isEmpty(etPerson) || EmptyUtils.isEmpty(face_id)) {
                    showToastMsg("请填写完整信息");
                    return;
                }*/
                gotoUpdateUser();
            }
        });
        m_navigationBar.setRightMenu(widgetButton);
    }

    private void gotoUpdateUser() {
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
//                htmlBean = (HtmlBean) o;
                if(EmptyUtils.isNotEmpty(upLoadPicEntity.Data)){
                    SPUtils.setShareString(Constants.USERIMG, upLoadPicEntity.Data.imgurl);

                }
                SPUtils.setShareString(Constants.USERIMGID, face_id);
                SPUtils.setShareString(Constants.USERIMGPERSON, getEditTextStr(etPerson));
                showToastMsg("修改成功");
                RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.UPDATE_INFO, true));
                onBackPressed();

            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

//        jpushid = JPushInterface.getRegistrationID(this);
        ModifyInfoMethods.getInstance().guideMaintain(subscriber, SPUtils.getShareInt(Constans.UID) + "", SPUtils.getShareString(Constans.HASHID), face_id, getEditTextStr(mEtName), getEditTextStr(etPerson));
        rxManager.add(subscriber);
    }

  /*  private void gotoUpdateUser() {
        showProgressingDialog();
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.UPDATE_INFO, true));
                onBackPressed();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });


        UpdateUserMethods.getInstance().saveData(subscriber,uid,hashid,info.detail_id,getEditTextStr(mEtName),birth,face_id,person_sex);
        rxManager.add(subscriber);
    }*/

    private void goChooseBirthDay() {
        Calendar startTime = Calendar.getInstance();
        int year = startTime.get(Calendar.YEAR);    //获取年
        int month = startTime.get(Calendar.MONTH);   //获取月份，0表示1月份
        int day = startTime.get(Calendar.DAY_OF_MONTH);    //获取当前天数
        startTime.set(year, month, day);
        Calendar endTime = Calendar.getInstance();
        endTime.set(1930, 0, 1);
        Calendar selectTime = Calendar.getInstance();
        MyDatePickerRepaymentDate myDatePickerCallBack = new MyDatePickerRepaymentDate();
        BottomPickerUtils.showDatePicker(this, endTime, startTime, selectTime, myDatePickerCallBack);
    }

    private void initSexOptionsPicker() {
        siteTypeStrList.clear();
        siteTypeStrList.add("男");
        siteTypeStrList.add("女");

        siteTypePicker = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (options1 == 0) {
                    person_sex = "1";//男的
                } else if (options1 == 1) {
                    person_sex = "2";
                }
                mTvSex.setText(siteTypeStrList.get(options1));

            }
        }).setSubmitText(getString(R.string.insure)).
                setCancelText(getString(R.string.cacal)).
                build();
        siteTypePicker.setPicker(siteTypeStrList);
    }

    @Override
    protected void setNavigation() {
        setNavigationBack("导购信息维护");
    }


    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }

    private class MyDatePickerRepaymentDate implements BottomPickerUtils.DatePickerCallback {

        @Override
        public void onDateSelect(Calendar calendar) {
            int year = calendar.get(Calendar.YEAR);    //获取年
            int month = calendar.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
            int day = calendar.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int min = calendar.get(Calendar.MINUTE);
            birth = year + "-" + month + "-" + day;
            mTvDate.setText(birth);
            System.out.println(year + "----------" + month + "月" + day + "日" + hour + "时" + min + "分钟");
        }
    }

    /*图片上传*/
    private RationaleListener mRationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            new AlertDialog.Builder(InfoCompileActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("没有权限您不能使用相机，请把相机权限赐给我吧!(如果设置不再提示,您可以在设置中打开权限)")
                    .setPositiveButton("好，给你", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();// 用户同意继续申请。
                        }
                    })
                    .setNegativeButton("我拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel(); // 用户拒绝申请。
                        }
                    }).show();
        }
    };
    //点击头像弹出popwindow
    private PicPopupWindow popupWindow;
    //存储头像
    private String filePath = "";
    private CreateBmpFactory mCreateBmpFactory;
    private Bitmap bmp;
    public static final int REQUEST_CODE_CAMERA = 1000;
    public static final int REQUEST_CODE_GALLERY = 1001;
    private TextView tv_cancel;
    private TextView tv_camera;
    private TextView tv_photo;

    public class PicPopupWindow extends PopupWindow {
        public PicPopupWindow(Context mContext, View parent) {
            View view = View.inflate(InfoCompileActivity.this, R.layout.pop_payback_select, null);
            tv_photo = (TextView) view.findViewById(R.id.tv_plan_repayment);//相册
            tv_photo.setText("相册");
            tv_camera = (TextView) view.findViewById(R.id.tv_plan_consume);//相机
            tv_camera.setText("相机");
            tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            tv_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            filePath = resultList.get(0).getPhotoPath();
                            bmp = mCreateBmpFactory.getBitmapByOpt(filePath);
//                            ivFace.setImageBitmap(bmp);
                            //上传头像
                            if (!"".equals(filePath)) {
//                                setPicToNet(bmp);
//                                ivFace.setImageBitmap(bmp);
                                ImageLoaderUtils.displayCircle(mIvFace, filePath);
                                setPicToNet(bmp);
                            }
                            popupWindow.dismiss();
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {

                        }
                    });
                }
            });
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            tv_photo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            filePath = resultList.get(0).getPhotoPath();
                            bmp = mCreateBmpFactory.getBitmapByOpt(filePath);
                            //上传头像
                            if (!"".equals(filePath)) {
//                                ivFace.setImageBitmap(bmp);
                                ImageLoaderUtils.displayCircle(mIvFace, filePath);
                                setPicToNet(bmp);
                            }
                            popupWindow.dismiss();
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {

                        }
                    });
                }
            });
            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_in_a));
            setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setFocusable(true);
            showAsDropDown(view);
            setOutsideTouchable(true);
            setBackgroundDrawable(getResources().getDrawable(R.color.bg_title2));
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
        }
    }

    @PermissionYes(105)
    private void openPic() {
        popupWindow = new PicPopupWindow(this, mIvFace);
    }

    @PermissionNo(105)
    private void injectPic() {
        popupWindow.dismiss();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，剩下的 AndPermission 自动完成。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToNet(final Bitmap bmp) {
        showProgressingDialog();
        new Thread() {
            @Override
            public void run() {
                byte[] photodata = GraphicsBitmapUtils.Bitmap2Bytes(bmp);
                Map parameters = new HashMap();
                String time = System.currentTimeMillis() + "";
                parameters.put("time", time);
                parameters.put("hash", SortUtils.getMyHash("fileNameuploadFile", "time" + time, "uid" + uid, "hashid" + hashid, "tags"));
                parameters.put("apiId", Constans.ANDROID_APP_ID);
                parameters.put("terminal", "3");
                parameters.put("fileName", "uploadFile");
                parameters.put("uid", "" + uid);
                parameters.put("hashid", hashid);
                parameters.put("tags", "");
                try {
//                    LogUtil.d(HttpUrl.uploadFace + "       -------->" + parameters + "-------->" + filePath + "-------->" + photodata + "-------->" + "utf-8");
                    String s = HttpURLConnHelper.doPostSubmitBody(Constants.BaseUrl + "api/Upload/uploadImg", parameters, filePath, photodata, "utf-8");
                    if (s != null) {
                        Message message = new Message();
                        message.obj = s;
                        message.what = 888;
                        handler.sendMessage(message);
                    } else {
                        dismissProgressDialog();
//                        ToastCommom.createToastConfig().ToastShow(CompileInfoActivity.this, "网络开小差啦,请稍后重试", getResources().getColor(R.color.white));
                        showToastMsg("请稍等");
                    }

                } catch (Exception e) {
//                    LogUtil.e("上传图片---" + e);
                    dismissProgressDialog();
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }

    UpLoadPicEntity upLoadPicEntity = new UpLoadPicEntity();
    private String face_id = "";
    private HandlerHelper handler = new HandlerHelper(this) {
        @Override
        protected void handleMessage(Object reference, Message msg) {
            switch (msg.what) {

                case 888:
                    dismissProgressDialog();

                    if (msg.obj != null) {
                        String res = msg.obj.toString();
                        System.out.println("dsds" + res);
                        if (upLoadPicEntity != null) {
                            try {
                                upLoadPicEntity = new Gson().fromJson(msg.obj.toString(), upLoadPicEntity.getClass());
                                if ("000000".equals(upLoadPicEntity.Code)) {
                                    /*FaceBean faceBean = new FaceBean();
                                    faceBean = new Gson().fromJson(upLoadPicEntity.Data.data,faceBean.getClass());*/
                                    face_id = upLoadPicEntity.Data.imgid + "";

                                    System.out.println("faceid" + face_id);
                                    showToastMsg("上传成功");
                                    RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.MODIFYSUCCESS, true));
                                    //修改头像
//                                    circle_info_pic.setImageBitmap(bmp);
                                    //   GliderHelper.loadImage(filePath, circle_info_pic, null);
//                                    faceId = upLoadPicEntity.getData().getId() + "";
//                                    updataFace();
//                                    avatar = upLoadPicEntity.Data.avatar;
//                                    if(login_status==1){
//                                        SPUtils.setShareString(Constans.FACE_SHOPMAN,avatar);
//                                    }else if(login_status==2){
//                                        SPUtils.setShareString(Constans.FACE_SALES,avatar);
//                                    }
//                                    ImageLoaderUtils.display(ivAvatar,upLoadPicEntity.Data.path);
//                                    hash_choose_img = true;


                                } else {
                                    showToastMsg("请稍后再试");
                                    dismissProgressDialog();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
            }
        }
    };

}
